﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeStash.Addin.Core.Interfaces;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Settings;
using CodeStash.Addin.Core;

namespace CodeStash.Addin.ServiceImplementation
{
    [Export(typeof(ILoginDetails))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    class LoginDetailsService : ILoginDetails
    {
        private WritableSettingsStore settingsStore;
        private const string CollectionName = "CodeStash";
        private const string Token = "Token";
        private const string Password = "Password";
        private const string Login = "Login";

        public void SetStore<T>(T store)
        {
            settingsStore = store as WritableSettingsStore;
        }

        public Core.LoginDetails Load()
        {
            CheckCollection();
            LoginDetails login = new LoginDetails();
            if (settingsStore.GetPropertyCount(CollectionName) > 0)
            {
                login.EmailAddress = settingsStore.GetString(CollectionName, Login);
                login.Password = settingsStore.GetString(CollectionName, Password);
                login.Token = settingsStore.GetString(CollectionName, Token);
            }
            return login;
        }

        public void Save(Core.LoginDetails details)
        {
            CheckCollection();
            settingsStore.SetString(CollectionName, Login, details.EmailAddress);
            settingsStore.SetString(CollectionName, Password, details.Password);
            settingsStore.SetString(CollectionName, Token, details.Token);
        }

        private void CheckCollection()
        {
            if (!settingsStore.CollectionExists(CollectionName))
                settingsStore.CreateCollection(CollectionName);
        }
    }
}
